package com.ujoku.controller;

import com.labillusion.core.platform.exception.ResourceNotFoundException;
import com.labillusion.core.platform.web.pagination.PaginationForm;
import com.labillusion.core.platform.web.rest.RESTController;
import com.ujoku.context.ActionContext;
import com.ujoku.domain.Member;
import com.ujoku.domain.Message;
import com.ujoku.interceptor.LoginRequired;
import com.ujoku.service.MessageService;
import com.ujoku.view.domain.MessageView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
public class MessageController extends RESTController {

    private final Logger logger = LoggerFactory.getLogger(MessageController.class);

    @Autowired
    private MessageService messageService;

    @Autowired
    private ActionContext actionContext;

    @RequestMapping(value="/message", method = RequestMethod.PUT)
    @ResponseBody
    @LoginRequired
    public String updateMessage(){
        Member member = actionContext.getMember();

        messageService.updateByToMemberId(member.getUser_id());

        member.setUnreadCounts(0);
        actionContext.setMember(member);

        return "successfully";
    }

    @RequestMapping(value="/message/friend", method = RequestMethod.GET)
    @ResponseBody
    @LoginRequired
    public MessageView getFriend(HttpServletRequest request) {
        Member member = actionContext.getMember();

        Map<String, Object> query = new HashMap<>();
        query.put("toMemberId", member.getUser_id());
        query.put("type","friendApply");
        query.put("status",1);

        List<Message> list = messageService.selectList(query);
        if(list.size() == 0)
            throw new ResourceNotFoundException("can not found message");

        MessageView view = new MessageView(list);

        return view;
    }

    @RequestMapping(value="/message", method = RequestMethod.POST)
    @ResponseBody
    @LoginRequired
    public MessageView getMessage(@Valid @RequestBody PaginationForm form) {
        Member member = actionContext.getMember();
        Map<String, Object> query = form.getQueryMap();
        query.put("toMemberId", member.getUser_id());

        List<Message> list = messageService.selectList(query);
        if(list.size() == 0)
            throw new ResourceNotFoundException("can not found message");

        int count = messageService.selectCount(query);

        MessageView view = new MessageView(list);

        view.setCount(count);

        return view;
    }
}